package com.smartfactory.sail.controller;

import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartfactory.sail.config.HeaderWrapper;
import com.smartfactory.sail.config.OperRecord;
import com.smartfactory.sail.constant.header.UserEnum;
import com.smartfactory.sail.entity.User;
import com.smartfactory.sail.entity.enums.UserStatusEnum;
import com.smartfactory.sail.service.IUserService;
import com.smartfactory.sail.utils.StringUtils;
import com.smartfactory.sail.vo.PageParam;
import com.smartfactory.sail.vo.user.AddUserReq;
import com.smartfactory.sail.vo.user.ListUserResp;
import com.smartfactory.sail.vo.user.UserInfoResp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * @author 王巨壁
 * @title: UserController
 * @projectName smart-sail
 * @description: 员工管理
 * @date 2019/7/2716:19
 */
@RestController
@RequestMapping("bizzuser")
@Api(tags = "员工管理")
public class UserBizzController extends ControllerResponse {

    private IUserService iUserService;
    private PasswordEncoder passwordEncoder;

    public UserBizzController(IUserService iUserService, PasswordEncoder passwordEncoder) {
        this.iUserService = iUserService;
        this.passwordEncoder = passwordEncoder;
    }
    @OperRecord(content = "新增员工",level = 0)
    @PostMapping("add")
    @ApiOperation(value = "添加员工",notes = "添加员工")
    public ApiResponse<Long> add(@Validated @RequestBody AddUserReq addUserReq) {
        String staffNo = addUserReq.getStaffNo();
        if (!StringUtils.isIdentityCode(addUserReq.getIdcard())) {
            return fail("请检查身份证格式是否正确");
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("staffNo", staffNo).or().eq("phone", addUserReq.getPhone()).or().eq("idcard", addUserReq.getIdcard());
        List<User> list = iUserService.list(query);
        if ( list!=null&&list.size()>0) {
            for (User user : list) {
                String staffNo1 = user.getStaffNo();
                String idcard = user.getIdcard();
                String phone = user.getPhone();
                if (addUserReq.getStaffNo().equals(staffNo1)) {
                    return fail("员工编码已经存在");
                }
                if (addUserReq.getPhone().equals(phone)) {
                    return fail("手机号码已经存在");
                }
                if (addUserReq.getIdcard().equals(idcard)) {
                    return fail("身份证已经存在");
                }
            }
        }
        User user = new User();
        BeanUtils.copyProperties(addUserReq, user);
        user.setPassword(passwordEncoder.encode(user.getIdcard().substring(user.getIdcard().length() - 6)));
        user.setReallyName(user.getUsername());
        if (iUserService.save(user)) {
            return ok(user.getId());
        }
        return fail("保存失败");
    }

    @ApiOperation(value = "员工列表 分页|currentPage|size|sortType|sortField 必传", notes = "员工列表 分页|currentPage|size|sortType|sortField 必传")
    @PostMapping("list/{currentPage}/{size}/{sortType}/{sortField}")
    @HeaderWrapper(UserEnum.class)
    public ApiResponse<IPage> list(@RequestBody Map<String ,Object> queryParam,
        @PathVariable("currentPage")Long currentPage,
        @PathVariable("size")Integer size,
        @PathVariable("sortType")Integer sortType,
        @PathVariable("sortField")String sortField
    ) {
        PageParam pageParam = new PageParam(currentPage,size,sortType,sortField);
        IPage<ListUserResp> list = iUserService.getList(queryParam,pageParam);
        return ok(list);
    }

    @ApiOperation(value = "根据id获取员工详情", notes = "根据id获取详情")
    @GetMapping("info/{id}")
    public ApiResponse<User> getById(@PathVariable Long id) {
        return ok(iUserService.getById(id));
    }

    @OperRecord(content = "修改员工信息",level = 0)
    @ApiOperation(value = "根据id修改员工", notes = "根据id修改员工")
    @PostMapping("/update")
    public ApiResponse<Boolean> update(@RequestBody User user) {
        return ok(iUserService.updateById(user));
    }

    @ApiOperation(value = "获取所有在职员工列表id和姓名", notes = "获取所有在职员工列表id和姓名")
    @PostMapping("/getList")
    public ApiResponse<List<User>> getList() {
       return ok(iUserService.list(new QueryWrapper<User>().eq("status", UserStatusEnum.ZZ.getCode()).orderByDesc("updateTime").select("id", "username")));

    }

    @GetMapping("getListByDept/{deptId}")
    public ApiResponse<List<User>> getListByDept(@PathVariable("deptId") Long deptId) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("deptId", deptId).orderByDesc("updateTime").select("id", "username");
        return ok(iUserService.list(query));
    }

    @GetMapping("/{userId}")
    public ApiResponse<UserInfoResp> userInfo(@PathVariable Long userId) {
        return ok(iUserService.userInfo(userId));
    }
}
